package com.monkeygroup.mygoplus.view.entrance.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.mob.tools.utils.UIHandler;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.common.utils.VilidateUtil;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.monkeygroup.mygoplus.view.entrance.activity.EntranceActivity;

import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.facebook.Facebook;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.google.GooglePlus;
import cn.sharesdk.line.Line;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by Administrator on 2017/3/9.
 */
public class LoginThirdFragment extends Fragment implements View.OnClickListener, Handler.Callback, PlatformActionListener {
    private View mView, nView;
    private final String TAG = "LoginThirdFragment";

    private static final int MSG_LOGIN = 1;
    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR = 3;
    private static final int MSG_AUTH_COMPLETE = 4;

    private Handler handler;


    private Activity activity;
    private Spinner choosespinner;
    private TextView txtDirectLogin;
    private TextView btn_login_google;
    private TextView btn_login_facebook;
    private TextView btn_login_line;
    private TextView btn_login_wechat_2;
    private TextView btn_login_wechat;
    private TextView btn_login_sina;
    private TextView btn_login_qq;
    private LinearLayout wechat1, sina, qq,
            wechat2, google, facebook, line;
    private LinearLayout.LayoutParams linear1, linear2;

    //头部
    private TextView txtTitle;
    private ImageView imgBack;


    // Fragment管理对象
    private FragmentManager manager;
    private FragmentTransaction ft;

    //請求參數
    private Map<String, String> params;
    private HttpModel httpModel;

    //三方登陆类型
    private String LoginType;
    //唯一ID，最好是手机号
    private String uniqueUserId;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView == null) {

            mView = inflater.inflate(R.layout.fragment_login_3rd_2, container, false);
            nView = inflater.inflate(R.layout.fragment_login_3rd_1, container, false);
            manager = getFragmentManager();

            initView();
            initListener();
            handler = new Handler(this);
            ShareSDK.initSDK(activity.getApplicationContext(), "1c615185e4e7e");
            initRequest();
        }
        return mView;
    }

    private void initView() {
        params = new HashMap<>();
        activity = this.getActivity();
        txtTitle = (TextView) mView.findViewById(R.id.txt_title);
        txtTitle.setText("第三方登入");
        imgBack = (ImageView) mView.findViewById(R.id.img_back);

        btn_login_google = (TextView) mView.findViewById(R.id.btn_login_google);
        btn_login_facebook = (TextView) mView.findViewById(R.id.btn_login_facebook);
        btn_login_line = (TextView) mView.findViewById(R.id.btn_login_line);
        btn_login_wechat_2 = (TextView) mView.findViewById(R.id.btn_login_wechat_2);
        txtDirectLogin = (TextView) mView.findViewById(R.id.txt_direct_login);
        btn_login_wechat = (TextView) nView.findViewById(R.id.btn_login_wechat);
        btn_login_sina = (TextView) nView.findViewById(R.id.btn_login_sina);
        btn_login_qq = (TextView) nView.findViewById(R.id.btn_login_qq);
        google = (LinearLayout) mView.findViewById(R.id.third_login_2_button_linearlayout_google);
        facebook = (LinearLayout) mView.findViewById(R.id.third_login_2_button_linearlayout_facebook);
        line = (LinearLayout) mView.findViewById(R.id.third_login_2_button_linearlayout_line);
        wechat2 = (LinearLayout) mView.findViewById(R.id.third_login_2_button_linearlayout_wechat);
        wechat1 = (LinearLayout) nView.findViewById(R.id.third_login_1_button_linearlayout_wechat);
        sina = (LinearLayout) nView.findViewById(R.id.third_login_1_button_linearlayout_sina);
        qq = (LinearLayout) nView.findViewById(R.id.third_login_1_button_linearlayout_qq);

        linear1 = (LinearLayout.LayoutParams) nView.findViewById(R.id.third_login_1_button_linearlayout).getLayoutParams();
        linear2 = (LinearLayout.LayoutParams) mView.findViewById(R.id.third_login_2_button_linearlayout).getLayoutParams();

        txtDirectLogin = (TextView) mView.findViewById(R.id.txt_direct_login);

        choosespinner = (Spinner) mView.findViewById(R.id.choosespinner);

        String[] items = getResources().getStringArray(R.array.spingarr);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity, R.layout.myspinner, items);
        choosespinner.setAdapter(adapter);

    }

    private void initListener() {

        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().popBackStack();
            }
        });

        choosespinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) {
                    LinearLayout layout2 = (LinearLayout) mView.findViewById(R.id.third_login_2_button_linearlayout);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        layout2.setLayoutParams(new LinearLayout.LayoutParams(linear2));
                    }

                    layout2.removeAllViews();
                    layout2.addView(google);
                    layout2.addView(facebook);
                    layout2.addView(line);
                    layout2.addView(wechat2);
                } else if (i == 1) {
                    LinearLayout layout1 = (LinearLayout) nView.findViewById(R.id.third_login_1_button_linearlayout);
                    LinearLayout layout2 = (LinearLayout) mView.findViewById(R.id.third_login_2_button_linearlayout);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        layout2.setLayoutParams(new LinearLayout.LayoutParams(linear1));
                    }

                    layout2.removeAllViews();
                    layout1.removeView(wechat1);
                    layout1.removeView(sina);
                    layout1.removeView(qq);
                    layout2.addView(wechat1);
                    layout2.addView(sina);
                    layout2.addView(qq);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        mView.findViewById(R.id.btn_login_google).setOnClickListener(this);
        mView.findViewById(R.id.btn_login_facebook).setOnClickListener(this);
        mView.findViewById(R.id.btn_login_line).setOnClickListener(this);
        mView.findViewById(R.id.btn_login_wechat_2).setOnClickListener(this);
        mView.findViewById(R.id.txt_direct_login).setOnClickListener(this);
        nView.findViewById(R.id.btn_login_wechat).setOnClickListener(this);
        nView.findViewById(R.id.btn_login_sina).setOnClickListener(this);
        nView.findViewById(R.id.btn_login_qq).setOnClickListener(this);

    }

    private void initRequest() {
        httpModel = new HttpModel(RequestUrl.baseUrl + RequestUrl.thirdLoginUrl, params, new HttpModel.SimpleOnHttpRequestListener() {

            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                Map<String, Double> result = (HashMap) data;
                Log.e(TAG, "resultCode++++++++++++" + resultCode);
                if (VilidateUtil.isSuccess(resultCode)) {
                    if (result.get("isThird") == 1) {
                        Log.e(TAG, "后台请求验证：：+++++已注册+++++成功");
                        //登录容联云
                        ((EntranceActivity) activity).initECLoginConfig(uniqueUserId);

//                        MainActivity.gotoActivity(activity);
                    } else if (result.get("isThird") == 0) {
                        RegisterFragment register = RegisterFragment.getInstance("thirdLogin");
                        ft = manager.beginTransaction();
                        //当前的fragment会被RegisterFragment替换
                        ft.replace(R.id.fragment_container, register);
                        ft.addToBackStack(null);
                        ft.commit();
                    }
                } else {
                    Toast.makeText(activity, resultMsg, Toast.LENGTH_SHORT).show();
                }
            }
        }, true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login_google:
                LoginType = "google";
                Platform googlePlat = ShareSDK.getPlatform(GooglePlus.NAME);
                authorize(googlePlat);
                break;
            case R.id.btn_login_facebook:
                LoginType = "faceBook";
                Platform facebookPlat = ShareSDK.getPlatform(Facebook.NAME);
                authorize(facebookPlat);
                break;
            case R.id.btn_login_line:
                LoginType = "Line";
                Platform linePlat = ShareSDK.getPlatform(Line.NAME);
                authorize(linePlat);
                break;
            case R.id.btn_login_wechat_2:
                LoginType = "Wechat";
                Platform wechatPlat2 = ShareSDK.getPlatform(Wechat.NAME);
                authorize(wechatPlat2);
                break;
            case R.id.btn_login_wechat:
                LoginType = "Wechat";
                Platform wechatPlat = ShareSDK.getPlatform(Wechat.NAME);
                authorize(wechatPlat);
                break;
            case R.id.btn_login_sina:
                LoginType = "Sina";
                Platform sinaPlat = ShareSDK.getPlatform(SinaWeibo.NAME);
                authorize(sinaPlat);
                break;
            case R.id.btn_login_qq:
                LoginType = "QQ";
                Platform qqPlat = ShareSDK.getPlatform(QQ.NAME);
                authorize(qqPlat);
                break;
            case R.id.txt_direct_login:
                activity.finish();
                txtDirectLogin.setTextColor(getResources().getColor(R.color.forget_font));
                break;
            default:
                break;
        }
    }

    public void authorize(Platform plat) {
        // 判断指定平台是否已经完成授权
        if (plat.isValid()) {
            // 已经完成授权，直接读取本地授权信息，执行相关逻辑操作（如登录操作）
            String userId = plat.getDb().getUserId();
            if (!TextUtils.isEmpty(userId)) {
                UIHandler.sendEmptyMessage(MSG_LOGIN, this);
                login(plat.getName(), userId, null);
                plat.removeAccount(true);
                return;
            }
        }
        plat.setPlatformActionListener(this);
        plat.SSOSetting(false);
        plat.showUser(null);
    }


    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        if (i == Platform.ACTION_USER_INFOR) {
            Message msg = new Message();
            msg.what = MSG_AUTH_COMPLETE;
            msg.obj = new Object[]{platform.getName(), hashMap};
            handler.sendMessage(msg);
            uniqueUserId = platform.getDb().getUserId();
            login(platform.getName(), platform.getDb().getUserId(), hashMap);
            // 取消授权
            platform.removeAccount(true);
        }
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        if (i == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_ERROR);
        }
        throwable.printStackTrace();
    }

    @Override
    public void onCancel(Platform platform, int i) {
        if (i == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_CANCEL);
        }
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case MSG_AUTH_CANCEL: {
                //取消授权
                Toast.makeText(activity, "授权已取消", Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_AUTH_ERROR: {
                //授权失败
                Toast.makeText(activity, "授权失败", Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_AUTH_COMPLETE: {
                //授权成功
                Toast.makeText(activity, "授权成功", Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_LOGIN: {
                //授权成功
                //Toast.makeText(activity, "正在登录中...", Toast.LENGTH_SHORT).show();
            }
            break;
        }
        return false;
    }

    // 业务逻辑：登录处理
    private void login(String plat, String userId, HashMap<String, Object> userInfo) {
        //Toast.makeText(activity, "用户ID:"+userId, Toast.LENGTH_SHORT).show();
        Message msg = new Message();
        msg.what = MSG_LOGIN;
        msg.obj = plat;
        UIHandler.sendMessage(msg, this);
        params.put("thirdID", userId);
        params.put("thirdType", getLoginType(LoginType));
        httpModel.startRequest();
    }

    /**
     * 获取三方登录类型
     *
     * @param longinType
     * @return
     */
    private String getLoginType(String longinType) {
        if (longinType.equals("google")) {
            return "1";
        } else if (longinType.equals("faceBook")) {
            return "0";
        } else if (longinType.equals("Line")) {
            return "2";
        } else if (longinType.equals("Wechat")) {
            return "3";
        } else if (longinType.equals("Sina")) {
            return "5";
        } else if (longinType.equals("QQ")) {
            return "4";
        } else {
            return "6";
        }
    }

}
